package leetcode

import kotlinetc.println

//https://leetcode.com/problems/group-anagrams/
/**
Given an sort.getArray of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:

All inputs will be in lowercase.
The order of your output does not matter.
 */

//主要是构造每个 anagram 的特征，以特征作为key值
fun main(args: Array<String>) {

    println('a'.toInt())
    println(profileAnagram("aaaa"))

    groupAnagrams(arrayOf("eat", "tea", "tan", "ate", "nat", "bat")).println()
}

fun groupAnagrams(strs: Array<String>): List<List<String>> {

    val map = hashMapOf<String, ArrayList<String>>()
    strs.forEach {
        val profileAnagram = profileAnagram(it)
        if (map.containsKey(profileAnagram)) {
            map[profileAnagram]!!.add(it)
        } else {
            val list = ArrayList<String>()
            list.add(it)
            map[profileAnagram] = list
        }

    }
    return map.values.toList()
}

/**
 * 构造 Anagram 特征串
 * 只有 26 个字母
 */
fun profileAnagram(anagram: String): String {

    val profile = StringBuffer()
    val arr = Array(26, { 0 })
    anagram.forEach {
        arr[it.toInt() - 97]++
    }
    arr.forEach {
        profile.append(it)
    }
    return profile.toString()
}